﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class admin_project_UpdateProject : System.Web.UI.Page
{
    static Project currentProject;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlProjectName.Items.Clear();
            ltrDetails.Text = "hide";

            var projects = ApplicationGlobalVariables.KillDaBugsDatabase.Projects;

            foreach (Project item in projects)
            {
                var projectItem = new ListItem(item.Name, item.ProjectId.ToString());
                ddlProjectName.Items.Add(projectItem);
            }

            ddlProjectName.SelectedIndex = -1;
        }
    }

    protected void ddlProjectName_SelectedIndexChanged(object sender, EventArgs e)
    {
        ltrDetails.Text = "";
        currentProject = ApplicationGlobalVariables.KillDaBugsDatabase.Projects.Single(i => i.ProjectId == int.Parse(ddlProjectName.SelectedValue));

        // bind data to control for view before editing
        txtDescription.Text = currentProject.Description;
        txtCustomMessage.Text = currentProject.CustomMessage;
        chbActive.Checked = currentProject.IsActive;
    }

    protected void btnCreate_Click(object sender, EventArgs e)
    {
        // check if status is the same as old one
        if (chbActive.Checked == currentProject.IsActive)
        {
            ltrError.Text = "New status is the same as old one, nothing to update";
        }
        else
        {
            // on closing a project
            if (!chbActive.Checked)
            {
                // check if there are still opened bugs belong to that project
                var activeBugs = currentProject.Bugs.Where(i => i.Status != (int)BugManagement.Status.Closed);

                if (activeBugs.Any())
                {
                    ltrError.Text = "Error: There are still opened bugs in this project";
                    return;
                }
            }

            ProjectManagement projectManagement = new ProjectManagement(Master.Master.CurrentUserManagement.CurrentUser, currentProject);

            if (projectManagement.SetProjectStatus(currentProject.IsActive))
                ltrError.Text = "New status is set!";
            else
                ltrError.Text = "Cannot set new status due to Database error!";
        }
    }
}